﻿using System;
using System.Linq.Expressions;
using System.Reflection;
using MongoDB.Bson;

namespace MongoDAO.Builders
{
    [Serializable]
    public class GroupBuilder<T>
    {
        private readonly BsonDocument _document;

        public GroupBuilder()
        {
            _document = new BsonDocument();
        }

        internal BsonDocument Document
        {
            get { return _document; }
        }

        public GroupBuilder<T> AddKey(Expression<Func<T, object>> memberExpression)
        {
            var memberName = GetTMemberName(memberExpression);
            _document.Add(memberName, String.Format("${0}", memberName));
            return this;
        }

        private static string GetTMemberName(Expression<Func<T, object>> memberExpression)
        {
            var member = ((MemberExpression)memberExpression.Body).Member as PropertyInfo;
            if (member != null)
                return member.Name;
            throw new ArgumentNullException("memberExpression");
        }

        public override string ToString()
        {
            return _document.ToString();
        }
    }
}
